package com.android.projectsquirrel;
import java.util.ArrayList;
import java.util.List;

import android.app.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;

public class SurveyPart2 extends Activity {
	String chosenProfileName = "";
	String[] data = new String[2];
	String savedObservtaion = "";
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.surveypart2);
        Bundle extras = getIntent().getExtras();
         data = extras.getStringArray("data");
         
        String[]  predators= new String[] {"Never","Low(1-2 per week)","Medium(3-4 per week)","High(5+ per week)"};
        String[] dogs = new String[] {"None","Low(1-2 per day)","Medium(3-4 per day)","High(5+ per day)"};
        String[]  foodlist = new String[] {"Never","Seldom","Often","Regularly"};
        
       
	        Spinner dogSpinner1 = (Spinner) findViewById(R.id.dogSpinner);
	        ArrayAdapter<String> dog_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, dogs);
	        dog_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        dogSpinner1.setAdapter(dog_adapter);
//	        dogSpinner1.setSelection(0);
	        
	        Spinner catSpinner = (Spinner) findViewById(R.id.catSpinner);
	        ArrayAdapter<String> cat_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, dogs);
	        cat_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        catSpinner.setAdapter(cat_adapter);
//	        catSpinner.setSelection(0);
	
	        Spinner coyoteSpinner = (Spinner) findViewById(R.id.coyoteSpinner);
	        ArrayAdapter<String> coyote_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item,predators);
	        coyote_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        coyoteSpinner.setAdapter(coyote_adapter);
//	        coyoteSpinner.setSelection(0);
	        
	        Spinner hawksSpinner = (Spinner) findViewById(R.id.hawksSpinner);
	        ArrayAdapter<String> hawks_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, predators);
	        hawks_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        hawksSpinner.setAdapter(hawks_adapter);
//	        hawksSpinner.setSelection(0);
	        
	        
	        Spinner poisonedGrainSpinner = (Spinner) findViewById(R.id.grainSpinner);
	        ArrayAdapter<String> grain_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, predators);
	        grain_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        poisonedGrainSpinner.setAdapter(grain_adapter);
//	        poisonedGrainSpinner.setSelection(0);
	        
	        Spinner birdFeederSpinner = (Spinner) findViewById(R.id.birdfeederSpinner);
	        ArrayAdapter<String> bird_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, foodlist);
	        bird_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        birdFeederSpinner.setAdapter(bird_adapter);
//	        birdFeederSpinner.setSelection(0);
	        
	        Spinner humanFeederSpinner = (Spinner) findViewById(R.id.humanHandoutSpinner);
	        ArrayAdapter<String> human_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, foodlist);
	        human_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        humanFeederSpinner.setAdapter(human_adapter);
//	        humanFeederSpinner.setSelection(0);
	        
	        Spinner garbageFeederSpinner = (Spinner) findViewById(R.id.garbageSpinner);
	        ArrayAdapter<String> garbage_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, foodlist);
	        garbage_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        garbageFeederSpinner.setAdapter(garbage_adapter);
//	        garbageFeederSpinner.setSelection(0);
	        
	        Spinner treeFeedSpinner = (Spinner) findViewById(R.id.treeFoodSpinner);
	        ArrayAdapter<String> treeFeed_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, foodlist);
	        treeFeed_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        treeFeedSpinner.setAdapter(treeFeed_adapter);
//	        treeFeedSpinner.setSelection(0);
	        

	        Spinner otherFoodSpinner = (Spinner) findViewById(R.id.otherSourcesSpinner);
	        ArrayAdapter<String> otherFeed_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, foodlist);
	        otherFeed_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        otherFoodSpinner.setAdapter(otherFeed_adapter);
//	        otherFoodSpinner.setSelection(0);
	        
	        Spinner foodDetailSpinner = (Spinner) findViewById(R.id.otherSourcesSpinner);
	        ArrayAdapter<String> foodDetails_adapter = new ArrayAdapter<String>(this,
	                    android.R.layout.simple_spinner_item, foodlist);
	        foodDetails_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        foodDetailSpinner.setAdapter(foodDetails_adapter);
//	        foodDetailSpinner.setSelection(0);
	        if("No".equals(data[1])){
	        	dogSpinner1.setSelection(0);
	        	 catSpinner.setSelection(0);
	        	 coyoteSpinner.setSelection(0);
	        	 hawksSpinner.setSelection(0);
	        	 poisonedGrainSpinner.setSelection(0);
	        	 birdFeederSpinner.setSelection(0);
	        	 humanFeederSpinner.setSelection(0);
	        	 garbageFeederSpinner.setSelection(0);
	        	  treeFeedSpinner.setSelection(0);
	        	  otherFoodSpinner.setSelection(0);
	        	  foodDetailSpinner.setSelection(0);
	        }
//       
        else{
        	populateFields(data[0]);
        }
        Button squirrelInfoButton = (Button) findViewById(R.id.saveSquirrelInfo);
        squirrelInfoButton.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view) {
            	Boolean okToProceed = checkForErrors();
            	if(okToProceed){
        			insertData2();
	            	Intent myIntent = new Intent(view.getContext(), SurveyPart3.class);
	            	myIntent.putExtra("data",data);
	            	startActivity(myIntent);
            	}
        	}
        });
        
        Button continueButton = (Button) findViewById(R.id.squirrelInfo);
        continueButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	Boolean okToProceed = checkForErrors();
            	if(okToProceed){
            			insertData2();
            			testResult();
	            	Intent myIntent = new Intent(view.getContext(), SurveyPart3.class);
	            	myIntent.putExtra("data",data);
	            	startActivity(myIntent);
            	}
            }
        });
        
	}
	
	public String testResult(){
    	Context context = getApplicationContext();
    	String profiles = new String();
    	DBAdapterUpdated db = new DBAdapterUpdated(this);
    	db.open();
//    	EditText profileNameEdit = (EditText)findViewById(R.id.profileName);
//    	String name = profileNameEdit.getText().toString();
    	Cursor c = db.getTitle(data[0]);
    	startManagingCursor(c);
    	if(c.moveToFirst()){
    		
    		for(int i =0;i<34;i++){
    			if(c.getString(i)!=null)
    			 profiles = profiles.concat(c.getColumnName(i)+"  "+c.getString(i));
    		}
    		
    	}
//    	showAlert(profiles);
		c.close();
    	db.close();
    	return profiles;
	 }
	
	public Boolean checkForErrors(){
		Boolean ok = true;
		String questionNumbers = "Please answer the following survey questions: \n";
		
		Spinner checkDogs = (Spinner) findViewById(R.id.dogSpinner);
		if(checkDogs.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 8. Please select a valid response for dogs near the site.\n");
			ok = false;
			
		}
		Spinner checkCats = (Spinner) findViewById(R.id.catSpinner);
		if(checkCats.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 8. Please select a valid response for cats near the site.\n");
			ok = false;
			
		}
		
		Spinner checkCoyotes = (Spinner) findViewById(R.id.coyoteSpinner);
		if(checkCoyotes.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 9. Please select a valid response for coyotes near the site.\n");
			ok = false;
			
		}
		Spinner checkHawks = (Spinner) findViewById(R.id.hawksSpinner);
		if(checkHawks.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 9. Please select a valid response for hawks near the site.\n");
			ok = false;
			
		}
		Spinner checkGrain = (Spinner) findViewById(R.id.grainSpinner);
		if(checkGrain.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 9. Please select a valid response for Poisoned Grain near the site.\n");
			ok = false;
			
		}
		
		if(ok == false){
			showAlert(questionNumbers);
		}
		return ok;
	}
	
	public void showAlert(String str){
		 // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

        // set the message to display
        alertbox.setMessage(str);

        // add a neutral button to the alert box and assign a click listener
        alertbox.setNegativeButton("Ok", new DialogInterface.OnClickListener() {

            // click listener on the alert box
            public void onClick(DialogInterface arg0, int arg1) {
            }
        });

        // show it
        alertbox.show();
	}
	
//	public void populateSpinnerItems(){
//		final Spinner usersChoiceSpinner = (Spinner) findViewById(R.id.userQuestion);
//		final List<String> items = new ArrayList<String>();
//		items.add(" ");
//		items.addAll(displayData());
//        ArrayAdapter<String> choice_adapter1 = new ArrayAdapter<String>(this,
//                    android.R.layout.simple_spinner_item, items);
//        choice_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        usersChoiceSpinner.setAdapter(choice_adapter1);
////        usersChoiceSpinner.setSelection(2);
//        usersChoiceSpinner.setOnItemSelectedListener(new
//                OnItemSelectedListener()
//         {
//        	public void onItemSelected(AdapterView parent, View v, int position,
//                long id){
//        			int pos = usersChoiceSpinner.getSelectedItemPosition();
//        			chosenProfileName = items.get(pos);
//        			populateFields(chosenProfileName);
//        	}
//        	 public void onNothingSelected(AdapterView arg0) {}
//
//           	});
//	}
	
	
	
	 public void show(String s){
   	  Toast toast1 = Toast.makeText(this, s, Toast.LENGTH_LONG);
   	  toast1.show();
     }
	
	public void OnResume(){
		super.onResume();
		DBAdapter db = new DBAdapter(this);
		db.open();
	}
	
	public void onPause(){
		super.onPause();
		DBAdapter db = new DBAdapter(this);
		db.close();
	}
	
	public void populate(){
		Spinner submittedBeforeSpinner = (Spinner)findViewById(R.id.submittedData);
		String submitted = submittedBeforeSpinner.getSelectedItem().toString();
		if(submitted.equals("Yes")){
			EditText editProfile = (EditText)findViewById(R.id.profileName);
			String profile = editProfile.getText().toString();
			populateFields(profile);
			
			
		}
	}
	
	public void populateFields(String profile){
		DBAdapterUpdated db = new DBAdapterUpdated(this);
		CharSequence text;
		int i;
		db.open();
		Cursor c = db.getTitle(profile);
    	startManagingCursor(c);
    	if(c.moveToFirst()){
    		
        	Spinner dogSpinner = (Spinner)findViewById(R.id.dogSpinner);
        	Spinner catSpinner = (Spinner)findViewById(R.id.catSpinner);
        	Spinner coyoteSpinner = (Spinner)findViewById(R.id.coyoteSpinner);
        	Spinner hawksSpinner = (Spinner)findViewById(R.id.hawksSpinner);
        	Spinner grainSpinner = (Spinner)findViewById(R.id.grainSpinner);
        	Spinner birdfeederSpinner = (Spinner)findViewById(R.id.birdfeederSpinner);
        	Spinner handoutSpinner = (Spinner)findViewById(R.id.humanHandoutSpinner);
        	Spinner garbageSpinner = (Spinner)findViewById(R.id.garbageSpinner);
        	Spinner treefeedSpinner = (Spinner)findViewById(R.id.treeFoodSpinner);
        	Spinner otherSourcesSpinner = (Spinner)findViewById(R.id.otherSourcesSpinner);
        	EditText foodDetails  = (EditText)findViewById(R.id.foodDetailEdit);
        	if(c.getString(27)!=null){
        		i = Integer.parseInt(c.getString(27));
        		dogSpinner.setSelection(i);
        	}else{
        		dogSpinner.setSelection(0);
        	}
        	if(c.getString(28)!=null){
    			i = Integer.parseInt(c.getString(28));
    			catSpinner.setSelection(i);
    		}else{
    			catSpinner.setSelection(0);
    		}
    	if(c.getString(29)!=null){
    		i = Integer.parseInt(c.getString(29));
    		coyoteSpinner.setSelection(i);
    	}else{
    		coyoteSpinner.setSelection(0);
    	}
    	if(c.getString(30)!=null){
    		i = Integer.parseInt(c.getString(30));
    		hawksSpinner.setSelection(i);
    	}else{
    		hawksSpinner.setSelection(0);
    	}
    	if(c.getString(31)!=null){
    		i = Integer.parseInt(c.getString(31));
    		grainSpinner.setSelection(i);
    	}else{
    		grainSpinner.setSelection(0);
    	}
    	if(c.getString(20)!=null){
    		i = Integer.parseInt(c.getString(20));
    		birdfeederSpinner.setSelection(i);
    	}else{
    		birdfeederSpinner.setSelection(0);
    	}
    	if(c.getString(21)!=null){
    		i = Integer.parseInt(c.getString(21));
    		handoutSpinner.setSelection(i);
    	}else{
    		handoutSpinner.setSelection(0);
    	}
    	if(c.getString(22)!=null){
    		i = Integer.parseInt(c.getString(22));
    		garbageSpinner.setSelection(i);
    	}else{
    		garbageSpinner.setSelection(0);
    	}
    	if(c.getString(23)!=null){
    		i = Integer.parseInt(c.getString(23));
    		treefeedSpinner.setSelection(i);
    	}else{
    		treefeedSpinner.setSelection(0);
    	}
    	if(c.getString(24)!=null){
    		i = Integer.parseInt(c.getString(24));
    		otherSourcesSpinner.setSelection(i);
    	}else{
    		otherSourcesSpinner.setSelection(0);
    	}
    	if(c.getString(24)!=null){
    		text = c.getString(25);
    		foodDetails.setText(text);
    	}else{
    		foodDetails.setText("");
    	}
    	}
		c.close();
		db.close();
		
		
	}
	public void insertData2(){
    	DBAdapterUpdated db = new DBAdapterUpdated(this);
    	Spinner dogSpinner = (Spinner)findViewById(R.id.dogSpinner);
    	Spinner catSpinner = (Spinner)findViewById(R.id.catSpinner);
    	Spinner coyoteSpinner = (Spinner)findViewById(R.id.coyoteSpinner);
    	Spinner hawksSpinner = (Spinner)findViewById(R.id.hawksSpinner);
    	Spinner grainSpinner = (Spinner)findViewById(R.id.grainSpinner);
    	Spinner birdSpinner = (Spinner)findViewById(R.id.birdfeederSpinner);
    	Spinner handoutSpinner = (Spinner)findViewById(R.id.humanHandoutSpinner);
    	Spinner garbageSpinner = (Spinner)findViewById(R.id.garbageSpinner);
    	Spinner treefeedSpinner = (Spinner)findViewById(R.id.treeFoodSpinner);
    	Spinner otherSourceSpinner = (Spinner)findViewById(R.id.otherSourcesSpinner);
    	EditText feedDetail = (EditText)findViewById(R.id.foodDetailEdit);
    	
		 db.open();
		 Boolean id;
		 boolean ins;
		 	ins = db.insertSurveyPart2(
		 			data[0],
	        		dogSpinner.getSelectedItemPosition(),
	        		catSpinner.getSelectedItemPosition(),
	        		coyoteSpinner.getSelectedItemPosition(),
	        		hawksSpinner.getSelectedItemPosition(),
	        		grainSpinner.getSelectedItemPosition(),
	        		birdSpinner.getSelectedItemPosition(),
	        		handoutSpinner.getSelectedItemPosition(),
	        		garbageSpinner.getSelectedItemPosition(),
	        		treefeedSpinner.getSelectedItemPosition(),
	        		otherSourceSpinner.getSelectedItemPosition(),
	        		feedDetail.getText().toString()
	        		);
	        		        
	        db.close();
	}
	

	
	public void update(String name){
		DBAdapter db = new DBAdapter(this);
		EditText editProfile = (EditText)findViewById(R.id.profileName);
    	Spinner submittedBeforeSpinner = (Spinner)findViewById(R.id.submittedData);
    	EditText editLatitude = (EditText)findViewById(R.id.latitudeEditText);
    	EditText editLongitude = (EditText)findViewById(R.id.longitudeEditText);
    	Spinner settingSpinner = (Spinner)findViewById(R.id.environmentSpinner);
    	Spinner nutSpinner = (Spinner)findViewById(R.id.nutSpinner);
    	Spinner seedSpinner = (Spinner)findViewById(R.id.seedSpinner);
    	Spinner fruitSpinner = (Spinner)findViewById(R.id.fruitSpinner);
    	Spinner tinySpinner = (Spinner)findViewById(R.id.tinySpinner);
    	Spinner coniferousSpinner = (Spinner)findViewById(R.id.coniferousSpinner);
    	EditText otherSpinner = (EditText)findViewById(R.id.otherTrees);
    	Spinner dogSpinner = (Spinner)findViewById(R.id.dogSpinner);
    	Spinner catSpinner = (Spinner)findViewById(R.id.catSpinner);
    	Spinner coyoteSpinner = (Spinner)findViewById(R.id.coyoteSpinner);
    	Spinner hawksSpinner = (Spinner)findViewById(R.id.hawksSpinner);
    	Spinner grainSpinner = (Spinner)findViewById(R.id.grainSpinner);
    	 db.open();
		 Boolean id;
		 long ins;
    	
		id = db.updateTitle(
				editProfile.getText().toString(),
        		submittedBeforeSpinner.getSelectedItemPosition(),
        		editLatitude.getText().toString(),
        		editLongitude.getText().toString(),
        		settingSpinner.getSelectedItemPosition(),
        		nutSpinner.getSelectedItemPosition(),
        		seedSpinner.getSelectedItemPosition(),
        		fruitSpinner.getSelectedItemPosition(),
        		tinySpinner.getSelectedItemPosition(),
        		coniferousSpinner.getSelectedItemPosition(),
        		otherSpinner.getText().toString(),
        		dogSpinner.getSelectedItemPosition(),
        		catSpinner.getSelectedItemPosition(),
        		coyoteSpinner.getSelectedItemPosition(),
        		hawksSpinner.getSelectedItemPosition(),
        		grainSpinner.getSelectedItemPosition());
		db.close();

		
	}
	 public String displayData(){
    	Context context = getApplicationContext();
    	String profiles = new String();
    	DBAdapterUpdated db = new DBAdapterUpdated(this);
    	db.open();
    	Cursor c = db.getTitle(chosenProfileName);
    	startManagingCursor(c);
    	if(c.moveToFirst()){
//    	if(c!=null){
//    		c.moveToNext();
    		if(c.getColumnCount()!=0){
    			for(int i=0;i<34;i++){
    				 profiles = profiles.concat(c.getColumnName(i)+" "+ c.getString(i)+" \n");
    	    			
    		        }

    	}
    	else {
    		Toast toast = Toast.makeText(context, "There are no saved profiles", Toast.LENGTH_LONG);
			toast.show();	
    	}
    	}
    	c.close();
    	db.close();
//    	show(profiles);
    	return profiles;
    }
	
	 
	 public boolean onCreateOptionsMenu(Menu menu) {
	        boolean supRetVal = super.onCreateOptionsMenu(menu);
	        menu.add(Menu.NONE, 0, Menu.NONE, "Go Home");
	    	//.setIcon(android.R.drawable.);
		return supRetVal;
	}
	
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case 0:
	        	startActivity(new Intent(SurveyPart2.this, Main.class));
	            return true;
	    }
	    return false;
	}

}
